# coding=utf-8
import sys
import time

import requests
import urllib3

__author__ = 'tzq'
import hashlib

from basetools import tool


class HttpHelper:
    def __init__(self):
        self.tool = tool.Tool()
        self.orderno = "ZF20181190281aCd38Y"
        self.secret = "dc73490ef3174f6a9d2be03e9c5d1906"
        self.ip = "forward.xdaili.cn"
        self.port = "80"
        self.header = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
            'Accept-Encoding': 'deflate, br',
            'Connection': 'keep-alive',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
            'cache-control': 'no-cache',
        }
        # 解析页面

    def getHtml(self, pageurl, headers, encoding='utf8', proxy=False):
        if proxy:
            headers = self.setHeaders(headers)
            return self.requestProxy(pageurl, headers)
        return self.request(pageurl, headers, encoding)

    def setHeaders(self, headers):
        timestamp = str(int(time.time()))
        string = "orderno=" + self.orderno + "," + "secret=" + self.secret + "," + "timestamp=" + timestamp
        string = string.encode()
        md5_string = hashlib.md5(string).hexdigest()
        sign = md5_string.upper()
        auth = "sign=" + sign + "&" + "orderno=" + self.orderno + "&" + "timestamp=" + timestamp
        headers['Proxy-Authorization'] = auth
        return headers

    def requestProxy(self, pageurl, headers):
        try:
            ip_port = self.ip + ":" + self.port
            # 用proxies字典保存代理ip
            proxies = {"http": "http://" + ip_port, "https": "https://" + ip_port}
            urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
            r = requests.get(pageurl, headers=headers, proxies=proxies, verify=False, allow_redirects=False)
            r.encoding = 'utf8'
            response = r.text
            if r.status_code == 302 or r.status_code == 301:
                loc = r.headers['Location']
                print(loc)
                r = requests.get(loc, headers=headers, proxies=proxies, verify=False, allow_redirects=False)
                r.encoding = 'utf8'
                print(r.status_code)
                print(r.text)
                response = r.text
            return response
        except:
            print("Unexpected error:", sys.exc_info()[2])

    def request(self, pageurl, headers, encoding):
        try:
            # 用proxies字典保存代理ip
            r = requests.get(pageurl, headers=headers, verify=False, allow_redirects=False)
            r.encoding = encoding
            response = r.text;
            if r.status_code == 302 or r.status_code == 301:
                loc = r.headers['Location']
                print(loc)
                r = requests.get(loc, headers=headers, verify=False, allow_redirects=False)
                r.encoding = 'utf8'
                print(r.status_code)
                print(r.text)
                response = r.text;
            return response;
        except:
            print("Unexpected error:", sys.exc_info()[2])
